package cn.edu.sgu.www.mhxysy.observer.impl;

import cn.edu.sgu.www.mhxysy.consts.RedisKeyPrefixes;
import cn.edu.sgu.www.mhxysy.function.computer.attribute.impl.AdvancedPropertyComputer;
import cn.edu.sgu.www.mhxysy.observer.Observer;
import cn.edu.sgu.www.mhxysy.redis.RedisUtils;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 具体观察者-角色高级属性观察者
 * @author 沐雨橙风ιε
 * @version 1.0
 */
@Component
public class AdvancedPropertyObserver implements Observer {

    private final RedisUtils redisUtils;
    private final AdvancedPropertyComputer advancedPropertyComputer;

    @Autowired
    public AdvancedPropertyObserver(
            RedisUtils redisUtils,
            AdvancedPropertyComputer advancedPropertyComputer) {
        this.redisUtils = redisUtils;
        this.advancedPropertyComputer = advancedPropertyComputer;
    }

    @Override
    public synchronized void update(Object message) {
        // 得到角色ID
        String roleId = (String) message;

        // 计算角色高级属性
        Map<String, Integer> advancedProperty = advancedPropertyComputer.compute(roleId);

        // 添加到Redis缓存
        String key = RedisKeyPrefixes.PREFIX_ADVANCED_PROPERTY + roleId;

        redisUtils.set(key, JSON.toJSONString(advancedProperty), 7, TimeUnit.HOURS);
    }

}